package com.zzxx.service.impl;

import com.zzxx.entity.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzxx.exceptions.PriceException;
import com.zzxx.exceptions.QrException;
import com.zzxx.mapper.*;
import com.zzxx.service.TicketService;
import com.zzxx.utils.QrCodeCreateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import java.util.List;

@Service
//@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
public class TicketServiceImpl implements TicketService {
    @Autowired(required = false)
    private HttpServletRequest request;
    @Autowired
    private TicketMapper ticketMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserCouponMapper userCouponMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ManagerQrMapper managerQrMapper;
    @Autowired
    private GymMapper gymMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private TicketScheduleMapper ticketScheduleMapper;
    @Autowired
    private ManagerPowerMapper managerPowerMapper;
    @Autowired
    private RuleMapper ruleMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Ticket findOne(String tid) {
     Ticket ticket =ticketMapper.findOne(tid);
        return ticket;
    }

    @Override
    public PageInfo<Ticket> queryByGid(Integer start, Integer pageSize, String gid) {
        PageHelper.startPage(start,pageSize);
        TicketExample example = new TicketExample();
        example.createCriteria().andTickettypeEqualTo(0).andTargetidEqualTo(gid);
        List<Ticket> tickets = ticketMapper.selectByExample(example);
        PageInfo<Ticket> pageInfo=new PageInfo<>(tickets);
        return pageInfo;
    }

    @Override
    public PageInfo<Orders> queryTicketByUid(Integer start, Integer pageSize, String uid) {
        PageHelper.startPage(start,pageSize);
        List<Orders> orders = ordersMapper.findTicketByUid(uid);
        PageInfo<Orders> pageInfo=new PageInfo<>(orders);
        return pageInfo;
    }

    @Override
    public Orders findGymTicketByOid(String oid) {
        Orders orders = ordersMapper.findGymTicketByOid(oid).get(0);
        long time=orders.getCreatetime().getTime()+orders.getTicket().getEffectivetime()*86400000;
        orders.setLastTime(new Date(time));
        return orders;
    }

    @Override
    public void buy(Integer num, Orders order) throws PriceException {
        if (!"doNotUseCoupon".equals(order.getCouponid())){
            UserCoupon userCoupon = userCouponMapper.selectByPrimaryKey(order.getCouponid());
            userCoupon.setStatus(1);
            userCouponMapper.updateByPrimaryKey(userCoupon);
        }else{
            order.setCouponid(null);
        }
        userCouponMapper.selectByPrimaryKey(order.getCouponid());
        User loginUser = (User)request.getSession().getAttribute("loginUser");
        for(int i=0;i<num;i++){
            //生成uuid
            String uuid= UUID.randomUUID().toString().replace("-","");
            //生成核销码
            Integer hash=uuid.hashCode();
            hash=hash<0? -hash:hash;
            String hexHash=Integer.toHexString(hash);
            order.setHexhash(hexHash);
            //生成二维码
            String parent = request.getServletContext().getRealPath("work/qrcreate")+"/"+new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String newImageName = uuid+".jpg";
            File qrImgFile = new File(parent,newImageName);
            if (!qrImgFile.getParentFile().exists()) {
                qrImgFile.getParentFile().mkdirs();
            }
            String fileName = qrImgFile.getAbsolutePath();
            QrCodeCreateUtils.CodeCreate(hexHash,500,500,fileName,"jpg");
            fileName = fileName.substring(fileName.indexOf("\\work"));
            order.setQrsrc(fileName);
            //设置值
            order.setId(uuid);
            order.setStatus(0);
            order.setCreatetime(new Date());
            order.setObjtype(0);
            order.setContenttype(0);
            if ("doNotUseCoupon".equals(order.getCouponid())) order.setCouponid(null);
            ordersMapper.insert(order);
            User user = userMapper.selectByPrimaryKey(loginUser.getId());
            Double money = user.getMoney();
            if(money<=0||money<order.getPrice()){
                throw new PriceException("余额不足，请充值！");
            }else {
                user.setMoney(user.getMoney()-order.getPrice());
                int i1 = userMapper.updateByPrimaryKeySelective(user);
                if(i1==1){
                    System.out.println("购票成功");
                }else {
                    System.out.println("购票失败");
                }
            }
        }

    }

    @Override
    public String scanQr(MultipartFile uploadFile) throws Exception{

       //生成二维码保存路径
       String parent = request.getServletContext().getRealPath("work\\qrscan")+"\\"+new SimpleDateFormat("yyyy-MM-dd").format(new Date());
       String newImageName = UUID.randomUUID().toString().replaceAll("-","")+".jpg";
        File qrImgFile = new File(parent,newImageName);
       //保存二维码
       if (!qrImgFile.getParentFile().exists()) {
           qrImgFile.getParentFile().mkdirs();
       }
       uploadFile.transferTo(qrImgFile);
       //识别二维码
       String message = QrCodeCreateUtils.zxingCodeAnalyze(qrImgFile.getAbsolutePath());
       return message;

    }


    @Override
    public void checkMessage(String message, int checkType) throws QrException {
        //没有登录直接退出
        Manager manager = (Manager) request.getSession().getAttribute("loginManager");
        if (manager==null) throw new QrException("noLogin");
        //查找订单
        OrdersExample example = new OrdersExample();
        example.createCriteria().andHexhashEqualTo(message);
        List<Orders> orders = ordersMapper.selectByExample(example);
        //没查到退出
        if (orders.size()!=1) throw new QrException("noSearch");
        Orders order = orders.get(0);
        //没权限退出
        String objid = order.getObjid();
        if (order.getObjtype()==0){
            Ticket ticket = ticketMapper.selectByPrimaryKey(objid);
            Gym gym = gymMapper.selectByPrimaryKey(ticket.getTargetid());
            ManagerPowerExample powerExample = new ManagerPowerExample();
            powerExample.createCriteria().andManageridEqualTo(manager.getId()).andPowertypeEqualTo(0).andPoweridEqualTo(gym.getId()).andPowerlevelGreaterThanOrEqualTo(1);
            List<ManagerPower> managerPowers = managerPowerMapper.selectByExample(powerExample);
            if (managerPowers.size()==0) throw new QrException("noPower");
        }else if(order.getObjtype()==1){
            ManagerPowerExample powerExample = new ManagerPowerExample();
            powerExample.createCriteria().andManageridEqualTo(manager.getId()).andPowertypeEqualTo(1).andPoweridEqualTo(objid).andPowerlevelGreaterThanOrEqualTo(1);
            List<ManagerPower> managerPowers = managerPowerMapper.selectByExample(powerExample);
            if (managerPowers.size()==0) throw new QrException("noPower");
        }
        //已核销退出
        if (order.getStatus()==2) throw new QrException("scanDown");
        //订单状态改为2，代表已经核销
        order.setStatus(2);
        //设置扫码人员id
        order.setManagerid(manager.getId());
        //设置扫码方式
        order.setChecktype(checkType);

        if (order.getCouponid()!=null){
            //记录核销信息
            saveTicketWriteOff(order,manager.getId(),order.getCouponid());
            //删除对应优惠券
            userCouponMapper.deleteByPrimaryKey(order.getCouponid());
        }
        //写入票的修改
        ordersMapper.updateByPrimaryKey(order);
        //记录核销信息
        saveTicketWriteOff(order,manager.getId(),null);
    }

    public void saveTicketWriteOff(Orders order, String managerId, String ucouponId) throws QrException {
        ManagerQr managerQr = new ManagerQr();
        //设置id
        managerQr.setId(UUID.randomUUID().toString().replaceAll("-",""));
        //设置核销人员id
        managerQr.setManagerid(managerId);
        //设置核销信息type 0场馆票 1活动票 2优惠券
        managerQr.setType(order.getObjtype());
        if (ucouponId ==null){
            managerQr.setType(order.getObjtype());
            //设置核销对象id
            managerQr.setObjid(order.getObjid());
        }else{
            managerQr.setType(2);
            //设置核销对象id
            managerQr.setObjid(ucouponId);
        }
        //设置核销时间
        managerQr.setTime(new Date());

        //设置核销对象name
        if (managerQr.getType()==0){
            Ticket ticket = ticketMapper.selectByPrimaryKey(managerQr.getObjid());
            Gym gym = gymMapper.selectByPrimaryKey(ticket.getTargetid());
            managerQr.setObjname(gym.getName()+ticket.getName());
        }
        else if (managerQr.getType()==1){
            String name = activityMapper.selectByPrimaryKey(managerQr.getObjid()).getActivityname();
            managerQr.setObjname(name);
        }else if (managerQr.getType()==2){
            UserCoupon userCoupon = userCouponMapper.selectByPrimaryKey(ucouponId);
            String couponId = userCoupon.getCouponid();
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
            String name = "";
            Activity activity = activityMapper.selectByPrimaryKey(coupon.getTargetid());
            if (activity!=null){
                name = activity.getActivityname();
            }else{
                Ticket ticket = ticketMapper.selectByPrimaryKey(coupon.getTargetid());
                if (ticket!=null){
                    Gym gym = gymMapper.selectByPrimaryKey(ticket.getTargetid());
                    name = gym.getName()+ticket.getName();
                }else{
                    throw new QrException("noQr");
                }
            }
            managerQr.setObjname(name+coupon.getName());
        }
        //写入核销信息
        managerQrMapper.insert(managerQr);
    }

    @Override
    public void packageQrInfo(QrInfo qrInfo, String oid) {
        Orders orders = ordersMapper.selectByPrimaryKey(oid);
        qrInfo.setStatus(orders.getStatus());
        qrInfo.setSrc(orders.getQrsrc());
        if (orders.getObjtype()==0){
            qrInfo.setName(ticketMapper.selectByPrimaryKey(orders.getTicketid()).getName());
        }else{
            qrInfo.setName(activityMapper.selectByPrimaryKey(orders.getObjid()).getActivityname());
        }
    }

    @Override
    public void deleteNum(String id,String num) {
        int n = Integer.parseInt(num);
        TicketSchedule ticketSchedule = ticketScheduleMapper.selectByPrimaryKey(id);
            ticketSchedule.setLastnum(ticketSchedule.getLastnum()-n);
            ticketScheduleMapper.updateByPrimaryKey(ticketSchedule);

    }

    @Override
    public List<Ticket> findManagerTicket(String managerId, String gid) {
        //验证权限
        ManagerPowerExample mexample = new ManagerPowerExample();
        mexample.createCriteria().andManageridEqualTo(managerId).andPoweridEqualTo(gid).andPowerlevelGreaterThanOrEqualTo(2);
        List<ManagerPower> mp = managerPowerMapper.selectByExample(mexample);
        if (mp.size()!=1) return null;
        //查找场馆对应的票
        TicketExample example = new TicketExample();
        example.createCriteria().andTickettypeEqualTo(0).andTargetidEqualTo(gid);
        List<Ticket> tickets = ticketMapper.selectByExample(example);
        return tickets;
    }

    @Override
    public TicketAndRule findTar(String managerId, String tid) {
        //验证权限
        ManagerPowerExample mexample = new ManagerPowerExample();
        String gid = gymMapper.selectByPrimaryKey(ticketMapper.selectByPrimaryKey(tid).getTargetid()).getId();
        mexample.createCriteria().andManageridEqualTo(managerId).andPoweridEqualTo(gid).andPowerlevelGreaterThanOrEqualTo(2);
        List<ManagerPower> mp = managerPowerMapper.selectByExample(mexample);
        if (mp.size()!=1) return null;
        //创建Tar
        TicketAndRule tar = new TicketAndRule();
        //查找ticket
        Ticket ticket = ticketMapper.selectByPrimaryKey(tid);
        tar.setTicket(ticket);
        //查找rule
        RuleExample example = new RuleExample();
        example.createCriteria().andTargetidEqualTo(tid);
        List<Rule> rules = ruleMapper.selectByExample(example);
        if (rules.size()!=1) return null;
        tar.setRule(rules.get(0));
        return tar;
    }

    @Override
    public void updateTar(TicketAndRule tar) {
        //修改票信息
        Ticket ticket = tar.getTicket();
        ticketMapper.updateByPrimaryKey(ticket);
        //修改规则信息
        Rule rule = tar.getRule();
        ruleMapper.updateByPrimaryKey(rule);
    }

    @Override
    public void addTar(TicketAndRule tar) {
        //先创建ticket
        Ticket ticket = tar.getTicket();
        ticket.setId(UUID.randomUUID().toString().replaceAll("-",""));
        Rule rule = tar.getRule();
        rule.setId(UUID.randomUUID().toString().replaceAll("-",""));
        rule.setTargetid(ticket.getId());
        ticketMapper.insert(ticket);
        ruleMapper.insert(rule);
    }

    @Override
    public void delete(String tid) {
        ticketMapper.deleteByPrimaryKey(tid);
        RuleExample example = new RuleExample();
        example.createCriteria().andTargettypeEqualTo(0).andTargetidEqualTo(tid);
        ruleMapper.deleteByExample(example);
    }

    @Override
    public Boolean tui(String id,String time) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(time);
        TicketScheduleExample example = new TicketScheduleExample();
        TicketScheduleExample.Criteria criteria = example.createCriteria().andTicketidEqualTo(id).andDateEqualTo(parse);
        List<TicketSchedule> list = ticketScheduleMapper.selectByExample(example);
        TicketSchedule  ticketSchedule=list.get(0);
        Date starttime = ticketSchedule.getStarttime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(starttime);
        calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)-16);
        Date time1 = calendar.getTime();
        Date time2 = new Date();
        int i = time2.compareTo(time1);
        if(i==-1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public int tuiById(String id) {
        Orders order = ordersMapper.selectByPrimaryKey(id);
        order.setStatus(1);
        String tid = order.getTicketid();
        Date booktime = order.getBooktime();
        TicketScheduleExample ticketScheduleExample = new TicketScheduleExample();
        TicketScheduleExample.Criteria criteria = ticketScheduleExample.createCriteria().andTicketidEqualTo(tid).andDateEqualTo(booktime);
        List<TicketSchedule> ticketSchedules = ticketScheduleMapper.selectByExample(ticketScheduleExample);
        TicketSchedule ticketSchedule=ticketSchedules.get(0);
        ticketSchedule.setLastnum(ticketSchedule.getLastnum()+1);
        ticketScheduleMapper.updateByPrimaryKeySelective(ticketSchedule);
        Double price = order.getPrice();
        User loginUser = (User)request.getSession().getAttribute("loginUser");
        User user = userMapper.selectByPrimaryKey(loginUser.getId());
        user.setMoney(user.getMoney()+price);
        userMapper.updateByPrimaryKeySelective(user);
        System.out.println("退票成功");
        return ordersMapper.updateByPrimaryKeySelective(order);
    }


}
